package easy;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;

public class Solution_993 {

    public boolean isCousins(TreeNode root, int x, int y) {
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        Map<Integer, TreeNode> map = new HashMap<>();
        map.put(root.val, null);
        while (!map.isEmpty()) {
            if (map.size()>1 && map.containsKey(x) && map.containsKey(y) && map.get(x) != map.get(y)) {
                return true;
            }
            map.clear();
            int count = queue.size();
            for (int i = 0; i < count; i++) {
                TreeNode node = queue.poll();
                if (node.left != null) {
                    queue.add(node.left);
                    map.put(node.left.val, node);
                }
                if (node.right != null) {
                    queue.add(node.right);
                    map.put(node.right.val, node);
                }
            }
        }
        return false;
    }

    public static void main(String[] args) {
        Solution_993 model = new Solution_993();
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.left.left = new TreeNode(4);
        root.right = new TreeNode(3);
        root.right.right = new TreeNode(5);
        System.out.println(model.isCousins(root, 4, 5));
    }

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
